package org.jiangy.authentication;

import jakarta.annotation.Nullable;
import org.jiangy.usercenter.entity.User;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Optional;

/**
 * 会话助手，提供对当前用户会话的一些操作
 * 1. 获取会话用户信息
 * <p>创建时间: 2024/8/16 </p>
 *
 * @author <a href="mailto:jiangliu0316@outlook.com" rel="nofollow">蒋勇</a>
 */
@SuppressWarnings("unused")
public final class SessionHelper {

    private SessionHelper() {
    }

    @Nullable
    public static String getUsername() {
        if (getUserInfo().isPresent()) {
            return getUserInfo().get().getUsername();
        }
        return null;
    }

    @Nullable
    public static Long getUserId() {
        if (getUserInfo().isPresent()) {
            return getUserInfo().get().getId();
        }
        return null;
    }

    public static Optional<User> getUserInfo() {
        return getPrincipal();
    }

    @SuppressWarnings("unchecked")
    private static <T extends User> Optional<T> getPrincipal() {
        Object principal = SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        try {
            return Optional.of((T) principal);
        } catch (Exception e) {
            return Optional.empty();
        }
    }
}
